package com.jf.apply_car.controller;

import com.jf.apply_car.util.ResultJson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class FIleController {
    @PostMapping("/upload")
    @ResponseBody
    public ResultJson upload(MultipartFile file, String type, HttpServletRequest request) {
        if (file == null) {
            return ResultJson.error("上传文件为空");
        }
        /*获取文件原名称*/
        String originalFilename = file.getOriginalFilename();
        /*获取文件格式后缀*/
        /*断言*/
        assert originalFilename != null;
        String[] ofs = originalFilename.split("\\.");
        String ext = ofs[ofs.length - 1];
        /*生成新文件名*/
        String filename = UUID.randomUUID() + "." + ext;
        /*文件路径*/
        String filepath = "static/upload/" + type + "/";
        /*获取项目部署后的绝对路径*/
        String basepath = request.getRealPath("/");
        /*验证文件夹是否需要创建*/
        File uploadFile = new File(basepath + filepath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        /*存储图片*/
        try {
            file.transferTo(new File(uploadFile, filename));
        } catch (IOException e) {
            return ResultJson.error(e.getMessage());
        }
        /*封装json*/
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("filename", filepath + filename);
        return ResultJson.success(map);
    }
}
